<?php
	
	class tunghoanh extends story{
		
		public $patternUrl; 
		public $startPage = 1;
		
		public function getChapters($storyUrl, $storyId){

			
			
			$model = new Model();
			
			$model->where = "id = '" . $storyId . "' AND getlink_manual = 0";
			$model->getdata('truyen');
			$resultTruyen = $model->fetchOne();
			if(!$resultTruyen){
				echo 'het';
				exit();
			}
			$pos_start = strpos($storyUrl, '.html1');
			if($pos_start !== false){
			
				$storyUrl = str_replace('.html1', '.html', $storyUrl);
			}else{
				//echo $storyUrl;
			}
			
			$html = file_get_html($storyUrl);

			if(!$html){
				echo 'het';
				exit();
			}
			
			$i = 0;
			
			$main = $html->find('#table-cm',0)->find('.tr');
		
			//$main = $html->find('.tr')->children(0);
			
			if(!$main){ 
				echo 'het';
				exit();
			}
			
			$countChapter = count($main);
			
			$i = $countChapter - 1;
			$i = 0;
			//$main = $html->find('.tr');
			
			$indexChuong = 2;
			$indexTenChuong = 3;
			
			$patternTap = '/(Tập|Quyển) ([\d]*)/i';
			$patternChapt = '/(Chương) ([\d]*)/i';

			for($i; $i < $countChapter; $i++){
				
				$title =  $main[$i]->children(0)->children(0)->innertext;
				
				$chuongLink =  $main[$i]->children(0)->children(0)->attr['href'];
				
				preg_match($patternTap, $title, $matcheTap);
			
				preg_match($patternChapt, $title, $matcheChapt);
			
				if($matcheTap[2]){
					$tap = trim($matcheTap[2]);
					$_SESSION['tap'] = $tap;
				}else{
					$tap = $_SESSION['tap'];
				}
				
				if($matcheChap[2]){
					$matchChap = 'true';
					$chapt = (int) trim($matcheChap[2]);
					$_SESSION['last_chapt'] = $chapt;
				}else{
					/*
					 * Trường hợp không lấy được chap và link
					* vẫn lấy chapt bằng $_SESSION['last_chapt'] để sau này update bằng tay
					*/
					$matchChap = 'false';
					$chapt = (int) $_SESSION['last_chapt'] + 1;
					$_SESSION['chapts'][] = $chapt;
				}
				
				$_SESSION['last_chapt'] = $chapt;
				
				$index = $tap . '_' . $chapt;
				
				if($chuongLink){
				
					$links[$index] = array(
							'link' => $chuongLink,
							'title'=> $title,
							'tap'  => $tap,
							'chapt' => $chapt,
							//'session_last_chapt' => $_SESSION['last_chapt'],
							//'session_chapts'=>$_SESSION['chapts'],
							//'matchChap'	=> $matchChap,
							//'in_array'	=> $in_array,
								
					);
				}else{
					//Kiểm tra nếu có trường hợp Dom lỗi sẽ không lấy được attr
					// VD: <a title="Ví dụ "đầu tiên"" href="">
					$links[$index] = array('title'=> 'Error', 'href'=> 'Error');
				}
			}
			
			$html->__destruct();
			unset($ret);
		
			return $links;
			
		}
		
		
		
		
		
		public function autoGetChapters($story){
			$_SESSION['story_id'] = $story['id'];
			unset($_SESSION['last_chapt']);
			
			$model = new Model();
			$pos_start = strpos($story['getlink_source'], '.html1');
			if($pos_start !== false){
					
				$storyUrl = str_replace('.html1', '.html', $story['getlink_source']);
			}else{
				//echo $storyUrl;
			}
				
			$html = file_get_html($story['getlink_source']);
		
			if(!$html){
				echo 'het';
				exit();
			}
				
			/*
			 * Tìm chương mới nhất trong db của truyen_chuong_link
			 * Nếu không có tức là chưa scan manual lần nào hoặc không tồn tại chương link
			 */
			$model->where = "story_id = '" . $story['id'] . "'";
			$model->order = "thutu DESC";
			$model->getdata('truyen_chuong_link');
			$resultLastLink = $model->fetchOne();
	
			if(!$resultLastLink){
				echo 'het';
				exit();
			}
			
			$i = 0;
				
			$main = $html->find('#table-cm',0)->find('.tr');
		
			//$main = $html->find('.tr')->children(0);
				
			if(!$main){
				echo 'het';
				exit();
			}
				
			$countChapter = count($main);
			
			$newKey = 0;
			
			/*
			 * Lặp link ở tunghoanh để tìm link nào là mới nhất so với db ở server
			 * Nếu có thì gán index bằng vị trí index của dom .tr ở tunghoanh
			 */
			$chapt = 0;
			foreach($main as $key => $value){
				if($value->children(0)->children(0)->href == $resultLastLink['link']){
					
					$newKey = $key;
					$chapt = $resultLastLink['thutu'];
					$_SESSION['last_chapt'] = $chapt;
					
					break;
				}
			}
			
			
			/*
			 *  Bắt đầu từ index tiếp theo tức là index chứa chương link mới hơn
			 */
			for($i = $newKey + 1; $i < $countChapter; $i++){
				
				$title =  $main[$i]->children(0)->children(0)->innertext;
				$chuongLink =  $main[$i]->children(0)->children(0)->attr['href'];
				preg_match($patternTap, $title, $matcheTap);
				preg_match($patternChapt, $title, $matcheChapt);
			
				if($matcheTap[2]){
					$tap = trim($matcheTap[2]);
					$_SESSION['tap'] = $tap;
				}else{
					$tap = $_SESSION['tap'];
				}
			
				if($matcheChap[2]){
					$matchChap = 'true';
					$_SESSION['last_chapt'] = $chapt;
				}else{
					$matchChap = 'false';
					$chapt = (int) $_SESSION['last_chapt'] + 1;
					$_SESSION['chapts'][] = $chapt;
				}
			
				$_SESSION['last_chapt'] = $chapt;
			
				$index = $tap . '_' . $chapt;
			
				if($chuongLink){
			
					$links[$index] = array(
							'link' => $chuongLink,
							'title'=> $title,
							'tap'  => $tap,
							'chapt' => $chapt,
							//'session_last_chapt' => $_SESSION['last_chapt'],
							//'session_chapts'=>$_SESSION['chapts'],
							//'matchChap'	=> $matchChap,
							//'in_array'	=> $in_array,
			
					);
				}else{
					//Kiểm tra nếu có trường hợp Dom lỗi sẽ không lấy được attr
					// VD: <a title="Ví dụ "đầu tiên"" href="">
					$links[$index] = array('title'=> 'Error', 'href'=> 'Error');
				}
			}
				
				
			$html->__destruct();
			unset($ret);
		
			return $links;
				
		}
		
		/*
		 *  @param $links: mảng đa chiều chứa các thuộc tính: link, tap, thutu, title
		*/
		public function getChapterContentToFiles($links, $sourceData){
			$links = json_encode($links);
			//$links = str_replace('"','\"' , $links);
				
			set_time_limit(7200);
				
			$a = 'var RenderUrlsToFile, arrayOfUrls, system;
			
		
			system = require("system");
		
			/*
			Render given urls
			@param array of URLs to render
			@param callbackPerUrl Function called after finishing each URL, including the last URL
			@param callbackFinal Function called after finishing everything
			*/
		
		
			RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
			    var getFilename, next, page, retrieve, urlIndex, webpage;
			    urlIndex = 0;
			    webpage = require("webpage");
			    page = null;
				var file="";
			
			    next = function(status, url, file) {
			        page.close();
			        callbackPerUrl(status, url, file);
			        return retrieve();
			    };
					
			    retrieve = function() {
			        var url;
			        if (urls.length > 0) {
			            url = urls.shift();
						var linkData = url;
						url = url.link;
		
			            urlIndex++;
			            page = webpage.create();
			    
						//Them vao ---------------------------
						page.settings.loadImages=false;
						page.onResourceRequested = function(request, net) {
							//console.log(request.url);
						  	if (request.url.indexOf(\'http://tunghoanh.com/\') === 0 && request.url.indexOf(\'http://ajax.googleapis.com/\') === 0 && request.url.indexOf(\'http://mong.vn/\') === 0){
								net.abort();
							}else{
								//console.log(request.url);
							}
						}
		
						page.onConsoleMessage = function(msg) {
						    console.log(msg);
						};
		
						page.onLoadFinished = function() {
							page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
								page.evaluate(function(linkData) {
			
									if($("#chapter_content").html().length){
										trangthai = 1;
									}else{
										trangthai = 0;
									}
					
									if($(".ctitle").find("img").length == 0){
										linkData.is_image = true;
										linkData.image_get = 0;
									}else{
										linkData.is_image = false;
										linkData.image_get = 1;
									}
			    					$.ajax({
			    						url : \'http://mong.vn/abc.php?putChapterContent=1&sourceAlias=tunghoanh\',
			    						type: \'POST\',
			    						async: false,
			    						cache: false,
			    						data: {
						
											tap: linkData.tap,
											truyen_id: linkData.story_id,
											is_image: linkData.is_image,
											image_get: linkData.image_get,
											chapt: linkData.thutu,
											title: $(".ctitle").html(),
											content: $("#chapter_content").html(),
											truyen_chuong_link_id: linkData.id,
											trangthai: trangthai,
										},
		
			    						success: function(data){
			    							console.log(data);
			    						},
		
										error: function(jqxhr,textStatus,errorThrown){
				                       		console.log(jqxhr);
				                        	console.log(textStatus);
				                        	console.log(errorThrown);
				                        } //End of log error
		
			    					});// End ajax
		    					}, linkData); //End of try evaluation
	    						return next(status, url, file);
							}); //end page.include js
						}
		
			            page.open(url, function(status) {
			            	if(status === "success") {
			            		// page.onLoadFinished = function(status) {
								// }; // end page.onLoadFinished
		
			                }//Status==success
			            });
			        }else { // else if(urls.length) > 0
			            return callbackFinal();
			        }
			    };
			    return retrieve();
			};
			
		   	var arrayOfUrls = JSON.parse(\''.$links . '\');
			//arrayOfUrls = JSON.parse(arrayOfUrls);
			RenderUrlsToFile(arrayOfUrls, (function(status, url, file) {
		
			}), function() {
		    return phantom.exit();
			});';
				
			file_put_contents('phantomwebintro.js', $a);
			exec('phantomjs phantomwebintro.js', $a, $b);
				
			$count = count($a);
			$content_html = $a[$count - 1];
		
			//$html = file_get_html($href);
			//$content_html = $html->find('#chapter_content', 0)->innertext;
			//$html->__destruct();
		
			//return $content_html;
		
		
		}
		
		
		
		
		
		
		
		
		/*
		 *  @param $links: mảng đa chiều chứa các thuộc tính: link, tap, thutu, title
		 */
		public function getChapterContentToFiles1($links, $sourceData){
			$links = json_encode($links);
			//$links = str_replace('"','\"' , $links);
			
			set_time_limit(7200);
			
			$a = 'var RenderUrlsToFile, arrayOfUrls, system;
					

			system = require("system");
			
			/*
			Render given urls
			@param array of URLs to render
			@param callbackPerUrl Function called after finishing each URL, including the last URL
			@param callbackFinal Function called after finishing everything
			*/
			
			
			RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
			    var getFilename, next, page, retrieve, urlIndex, webpage;
			    urlIndex = 0;
			    webpage = require("webpage");
			    page = null;
				var file="";
			  
			    next = function(status, url, file) {
			        page.close();
			        callbackPerUrl(status, url, file);
			        return retrieve();
			    };
									
			    retrieve = function() {
			        var url;
			        if (urls.length > 0) {
			            url = urls.shift();
						var linkData = url;
						url = url.link;
						
			            urlIndex++;
			            page = webpage.create();
			          
						//Them vao ---------------------------
						page.settings.loadImages=false;
						page.onResourceRequested = function(request, net) {
							//console.log(request.url);
						  	if (request.url.indexOf(\'http://tunghoanh.com/\') === 0 && request.url.indexOf(\'http://ajax.googleapis.com/\') === 0 && request.url.indexOf(\'http://mong.vn/\') === 0){
								net.abort();
							}else{
								//console.log(request.url);
							}
						}
						
						page.onConsoleMessage = function(msg) {
						    console.log(msg);
						};
						
						page.onLoadFinished = function() {
							page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
								page.evaluate(function(linkData) {
					
									if($("#chapter_content").html().length){
										trangthai = 1;
									}else{
										trangthai = 0;
									}
									
									if($(".ctitle").find("img").length == 0){
										linkData.is_image = true;
										linkData.image_get = 0;
									}else{
										linkData.is_image = false;
										linkData.image_get = 1;
									}
			    					$.ajax({
			    						url : \'http://mong.vn/abc.php?putChapterContent=1&sourceAlias=tunghoanh\',
			    						type: \'POST\',
			    						async: false,
			    						cache: false,
			    						data: {
											
											tap: linkData.tap, 
											truyen_id: linkData.story_id,
											is_image: linkData.is_image,
											image_get: linkData.image_get,
											chapt: linkData.thutu, 
											title: $(".ctitle").html(), 
											content: $("#chapter_content").html(),
											truyen_chuong_link_id: linkData.id,
											trangthai: trangthai,
										},
						
			    						success: function(data){
			    							console.log(data);
			    						},
						
										error: function(jqxhr,textStatus,errorThrown){
				                       		console.log(jqxhr);
				                        	console.log(textStatus);
				                        	console.log(errorThrown);                               
				                        } //End of log error
						
			    					});// End ajax
		    					}, linkData); //End of try evaluation
	    						return next(status, url, file);
							}); //end page.include js		
						}
						
			            page.open(url, function(status) {
			            	if(status === "success") {
			            		// page.onLoadFinished = function(status) {         			
								// }; // end page.onLoadFinished
			                	
			                }//Status==success
			            });
			        }else { // else if(urls.length) > 0
			            return callbackFinal();
			        }
			    };
			    return retrieve();
			};
					
		   	var arrayOfUrls = JSON.parse(\''.$links . '\');
			//arrayOfUrls = JSON.parse(arrayOfUrls);
			RenderUrlsToFile(arrayOfUrls, (function(status, url, file) {
		  
			}), function() {
		    return phantom.exit();
			});';
			
			file_put_contents('phantomwebintro.js', $a);
			exec('phantomjs phantomwebintro.js', $a, $b);
			
			$count = count($a);
			$content_html = $a[$count - 1];
	
			//$html = file_get_html($href);
			//$content_html = $html->find('#chapter_content', 0)->innertext;
			//$html->__destruct();
	
			//return $content_html;
		
		
		}
		
		/* public function getChapterContent($href){
			echo '<pre>';
			print_r($href);
			echo '</pre>';
			set_time_limit(7200);
			$pos = strpos($href, 'http://');
			if($pos !== false){
				
				$a = 'var page = require(\'webpage\').create();

page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open("'.$href.'", function(status) {
    if ( status === "success" ) {
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", function() {
            page.evaluate(function() {
            	
                console.log($("#chapter_content").html());
            });
            phantom.exit();
        });
    }
});';
				file_put_contents('phantomwebintro.js', $a);
				exec('phantomjs phantomwebintro.js', $a, $b);

				$count = count($a);
				$content_html = $a[$count - 1];

				//$html = file_get_html($href);
				//$content_html = $html->find('#chapter_content', 0)->innertext;
				//$html->__destruct();
				
				return $content_html;
			}else{
				return false;
			}
		
		} */
		
	}